package com.huahai.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.huahai.cofig.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 腾讯云cos对象存储管理 - 通用配置类
 *
 * @author huahai
 */
@Slf4j
@Component
public class CosManager {

    @Resource
    private COSClient cosClient;

    @Resource
    CosClientConfig cosClientConfig;

    // 编写通用的方法

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     *
     * @param key 唯一键
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传对象（附带图片信息）
     *
     * @param key  数据万象处理后的图片文件名
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        // 对图片进行处理（获取基本信息也被视作为一种处理）
        PicOperations picOperations = new PicOperations();
        // 1 表示返回原图信息
        picOperations.setIsPicInfo(1);

        // 新增：对图片进行压缩操作
        // 1. 创建规则
        List<PicOperations.Rule> ruleList = new ArrayList<>();
        // 2. 进行压缩，转换为.webp格式
        String webpKey = FileUtil.mainName(key) + ".webp";

        // 3. 添加压缩规则
        PicOperations.Rule compressRule = new PicOperations.Rule();
        compressRule.setFileId(webpKey);
        compressRule.setBucket(cosClientConfig.getBucket());
        compressRule.setRule("imageMogr2/format/webp");
        ruleList.add(compressRule);
        picOperations.setRules(ruleList);

        // 新增：添加缩略图规则 约定：只对文件大小大于20kb的文件进行缩略处理
        if (file.length() > 2 * 1024) {
            // 修改压缩后的文件名
            String suffixUrl = FileUtil.getSuffix(key);
            String thumbnailKey;
            if (StrUtil.isBlank(suffixUrl)) {
                // 不存在自动补充png后缀
                thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + "png";
            } else {
                thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + suffixUrl;
            }
            // 添加缩略图规则
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setFileId(thumbnailKey);
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 256, 256));
            ruleList.add(thumbnailRule);
        }

        // 构造处理参数
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除原图
     *
     * @param bucketName 存储桶名
     * @param key        生成后的文件名
     */
    public void deleteOriginalImage(String bucketName, String key) {
        try {
            // 调用腾讯云 COS 的删除接口
            cosClient.deleteObject(bucketName, key);
            log.info("原图已从腾讯云存储中删除:{}{} ", bucketName, key);
        } catch (Exception e) {
            log.error("删除原图失败", e);
        }
    }


    /**
     * 删除图片通用接口
     *
     * @param key  生成后的文件名
     */
    public void deleteImage(String key) {
        try {
            // 调用腾讯云 COS 的删除接口
            cosClient.deleteObject(cosClientConfig.getBucket(), key);
            log.info("图片已从腾讯云存储中删除:{}", key);
        } catch (Exception e) {
            log.error("删除图片失败", e);
        }
    }


}
